package com.example.gokuplayalong.service.fragments.users.profile;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.R;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.beans.Beans;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.network.NetWorkInterface;
import com.example.gokuplayalong.bases.tools.Tools;
import com.example.gokuplayalong.service.fragments.others.UserMainPageAdapter;
import com.example.gokuplayalong.service.fragments.others.UserMainPageOrderListListViewHolder;
import com.example.gokuplayalong.service.fragments.users.receive.UserMainReceiveOrderDetail;
import com.example.gokuplayalong.service.fragmentsmanage.SysManagerFragments;
import com.huawei.hms.ads.App;
import com.kongzue.dialogx.dialogs.BottomMenu;
import com.kongzue.dialogx.dialogs.PopTip;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserMainProfileMyOrder#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class UserMainProfileMyOrder extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    View rootView;


    List<Beans> beans = new ArrayList<>();
    List<Beans> beansTemp = new ArrayList<>();
    UserMainPageAdapter userMainPageAdapter;
    private ImageView mUserMainProfileMyorderIv;
    private TextView mUserMainProfileMyorderAll;
    private TextView mUserMainProfileMyorderPaying;
    private TextView mUserMainProfileMyorderBooking;
    private TextView mUserMainProfileMyorderRunning;
    private TextView mUserMainProfileMyorderFinished;
    private RecyclerView mUserMainProfileMyorderRecyclerview;

    String selectedItem = "预约中";
    public Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {
                    try {
                        selectedItem = "预约中";
                        AppParams.getInstance().appRunParams.getJsonObject().put("chatNum", 1);

                        getOrderList();
                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                break;
                case 2: {
                    try {
                        selectedItem = "陪玩中";
                        AppParams.getInstance().appRunParams.getJsonObject().put("chatNum", 1);

                        getOrderList();
                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                break;
                case 3: {
                    try {
                        selectedItem = "已完成";
                        AppParams.getInstance().appRunParams.getJsonObject().put("chatNum", 1);

                        getOrderList();
                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                break;
            }
        }
    };

    public UserMainProfileMyOrder() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment UserMainProfileMyOrder.
     */
    // TODO: Rename and change types and number of parameters
    public static UserMainProfileMyOrder newInstance(String param1, String param2) {
        UserMainProfileMyOrder fragment = new UserMainProfileMyOrder();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_user_main_profile_my_order, container, false);
        initView();
        return rootView;
    }

    private void initView() {


        mUserMainProfileMyorderIv = rootView.findViewById(R.id.user_main_profile_myorder_iv);
        mUserMainProfileMyorderAll = rootView.findViewById(R.id.user_main_profile_myorder_all);
        mUserMainProfileMyorderPaying = rootView.findViewById(R.id.user_main_profile_myorder_paying);
        mUserMainProfileMyorderBooking = rootView.findViewById(R.id.user_main_profile_myorder_booking);
        mUserMainProfileMyorderRunning = rootView.findViewById(R.id.user_main_profile_myorder_running);
        mUserMainProfileMyorderFinished = rootView.findViewById(R.id.user_main_profile_myorder_finished);
        mUserMainProfileMyorderRecyclerview = rootView.findViewById(R.id.user_main_profile_myorder_recyclerview);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(rootView.getContext());
        mUserMainProfileMyorderRecyclerview.setLayoutManager(linearLayoutManager);

        userMainPageAdapter = new UserMainPageAdapter(beansTemp);
        mUserMainProfileMyorderRecyclerview.setAdapter(userMainPageAdapter);


        mUserMainProfileMyorderAll.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View view) {
                try {

                    if (!Tools.Deshak()) return;
                    selectedItem = "全部";
                    mUserMainProfileMyorderAll.setTextColor(Color.BLUE);
                    mUserMainProfileMyorderPaying.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderBooking.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderRunning.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderFinished.setTextColor(Color.BLACK);

                    if (!beansTemp.isEmpty()) beansTemp.clear();
                    beansTemp.addAll(beans);
                    userMainPageAdapter.notifyDataSetChanged();
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainProfileMyorderPaying.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    selectedItem = "待支付";
                    mUserMainProfileMyorderAll.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderPaying.setTextColor(Color.BLUE);
                    mUserMainProfileMyorderBooking.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderRunning.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderFinished.setTextColor(Color.BLACK);

                    if (!beansTemp.isEmpty()) beansTemp.clear();

                    for (int i = 0; i < beans.size(); i++) {
                        if (Objects.equals(beans.get(i)
                                .getJsonObject()
                                .getString("status"), "待支付")) {
                            beansTemp.add(beans.get(i));
                        }
                    }
                    userMainPageAdapter.notifyDataSetChanged();
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainProfileMyorderBooking.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    selectedItem = "预约中";

                    mUserMainProfileMyorderAll.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderPaying.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderBooking.setTextColor(Color.BLUE);
                    mUserMainProfileMyorderRunning.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderFinished.setTextColor(Color.BLACK);
                    if (!beansTemp.isEmpty()) beansTemp.clear();

                    for (int i = 0; i < beans.size(); i++) {
                        if (Objects.equals(beans.get(i)
                                .getJsonObject()
                                .getString("status"), "预约中")) {
                            beansTemp.add(beans.get(i));
                        }
                    }
                    userMainPageAdapter.notifyDataSetChanged();
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainProfileMyorderRunning.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    selectedItem = "陪玩中";

                    mUserMainProfileMyorderAll.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderPaying.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderBooking.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderRunning.setTextColor(Color.BLUE);
                    mUserMainProfileMyorderFinished.setTextColor(Color.BLACK);
                    if (!beansTemp.isEmpty()) beansTemp.clear();

                    for (int i = 0; i < beans.size(); i++) {
                        if (Objects.equals(beans.get(i)
                                .getJsonObject()
                                .getString("status"), "陪玩中")) {
                            beansTemp.add(beans.get(i));
                        }
                    }
                    userMainPageAdapter.notifyDataSetChanged();
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainProfileMyorderFinished.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    selectedItem = "已完成";

                    mUserMainProfileMyorderAll.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderPaying.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderBooking.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderRunning.setTextColor(Color.BLACK);
                    mUserMainProfileMyorderFinished.setTextColor(Color.BLUE);
                    if (!beansTemp.isEmpty()) beansTemp.clear();

                    for (int i = 0; i < beans.size(); i++) {
                        if (Objects.equals(beans.get(i)
                                .getJsonObject()
                                .getString("status"), "已完成")) {
                            beansTemp.add(beans.get(i));
                        }
                    }
                    userMainPageAdapter.notifyDataSetChanged();
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainProfileMyorderRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();

                    if (lastVisibleItemPosition == (AppParams.getInstance().appRunParams.getJsonObject()
                            .getIntValue("chatNum") * AppParams.getInstance().appRunParams.getJsonObject()
                            .getIntValue("chatCount")) - 1) {
                        AppParams.getInstance().appRunParams.getJsonObject()
                                .put("chatNum", AppParams.getInstance().appRunParams.getJsonObject()
                                        .getIntValue("chatNum") + 1);
                        getOrderList();
                    }

                }
            }
        });

        mUserMainProfileMyorderIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    SysManagerFragments.switchBackOnSysFragment();
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initChanged();
        }
        else {
            if (UserMainPageOrderListListViewHolder.bottomMenu != null)
                UserMainPageOrderListListViewHolder.bottomMenu.dismiss();
        }
    }

    private void initChanged() {
        try {
            AppParams.getInstance().appRunParams.getJsonObject().put("chatNum", 1);

            getOrderList();
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    private void getOrderList() {
        try {
            Beans beansIn = new Beans();
            beansIn.getJsonObject()
                    .put("phone", AppParams.getInstance().appCurrentUser.getJsonObject()
                            .getString("phone"));
            JSONObject merchantInfo = JSON.parseObject(AppParams.getInstance().appCurrentUser.getJsonObject()
                    .getString("merchantInfo"));
            beansIn.getJsonObject().put("merchantId", merchantInfo.getString("merchantid"));
            beansIn.getJsonObject()
                    .put("chatNum", AppParams.getInstance().appRunParams.getJsonObject()
                            .getIntValue("chatNum"));
            beansIn.getJsonObject()
                    .put("chatCount", AppParams.getInstance().appRunParams.getJsonObject()
                            .getIntValue("chatCount"));


            AppParams.getNewNetWork()
                    .setInterface(new NetWorkInterface() {
                        @SuppressLint("NotifyDataSetChanged")
                        @Override
                        public int success(String msg) {
                            try {
                                JSONObject msgFromServer = JSON.parseObject(msg);
                                if (msgFromServer.getString("result").equals("成功")) {
                                    JSONArray orderList = JSONArray.parseArray(msgFromServer.getString("orderList"));
                                    if (!beans.isEmpty()) beans.clear();
                                    for (int i = 0; i < orderList.size(); i++) {
                                        Beans item = new Beans();
                                        item.setJsonObject(orderList.getJSONObject(i));
                                        item.getJsonObject()
                                                .put("viewType", UserMainPageAdapter.VIEWTYPE_ORDER_LIST);
                                        beans.add(item);
                                    }
                                    requireActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            new Handler().postDelayed(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        UIRefrsh();
                                                    } catch (Throwable e) {
                                                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                                    }
                                                }
                                            }, 500);
                                        }
                                    });
                                }
                            } catch (Throwable e) {
                                ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                            }
                            return 0;
                        }

                        @Override
                        public int failed(String msg) {
                            return 0;
                        }
                    })
                    .execute(AppParams.getInstance().baseUrl + "/getOrderList", beansIn.getJsonObject()
                            .toJSONString());
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    void UIRefrsh() {
        if (Objects.equals(selectedItem, "全部")) {
            mUserMainProfileMyorderAll.performClick();
        }
        else if (Objects.equals(selectedItem, "待支付")) {
            mUserMainProfileMyorderPaying.performClick();
        }
        else if (Objects.equals(selectedItem, "预约中")) {
            mUserMainProfileMyorderBooking.performClick();
        }
        else if (Objects.equals(selectedItem, "陪玩中")) {
            mUserMainProfileMyorderRunning.performClick();
        }
        else if (Objects.equals(selectedItem, "已完成")) {
            mUserMainProfileMyorderFinished.performClick();
        }
    }
}